package com.ipzoe.web.core.i18n;

import cn.hutool.core.util.StrUtil;
import org.beetl.ext.struts2.Struts2BeetlActionResult;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Component
public class I18nUtil {

    public static final String ZH_CN = "zh_CN";
    public static final String ZH_TW = "zh_TW";

    private static final String I18N_COOKIE_NAME = "dans-i18n";

    private static final Integer EXP_SECONDES = 7 * 24 * 3600;

    private static MessageSource messageSource;

    public I18nUtil(MessageSource messageSource) {
        I18nUtil.messageSource = messageSource;
    }

    /**
     * 根据当前登陆用户选择的语言，翻译成指定编码对应语言的值
     */
    public static String get(String code) {
        try {
            return messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return code;
        }
    }

    /**
     * 设置当前用户选择的语种
     */
    public static void setLocaleToCookie(String newLocale, HttpServletResponse response) {
        if(!StrUtil.equalsAny(newLocale, ZH_CN, ZH_TW)){
            newLocale = ZH_CN;
        }
        Cookie languageCookie = new Cookie(I18N_COOKIE_NAME, newLocale);
        languageCookie.setMaxAge(EXP_SECONDES);
        languageCookie.setHttpOnly(true);
        languageCookie.setPath("/");
        response.addCookie(languageCookie);
    }

    /**
     * 获取当前用户选择的语种
     *
     * @author fengshuonan
     * @Date 2019/10/18 11:06
     */
    public static String getLocaleFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (I18N_COOKIE_NAME.equals(cookie.getName())) {
                    String value = cookie.getValue();
                    if (StrUtil.isNotEmpty(value)) {
                        return value;
                    }
                }
            }
        }
        //cookie没值，返回中文
        return ZH_CN;
    }

}
